var pageBean = null;
var dataList = {};
var provinces = {};
var cities = {};
var citySpace = {};
var spaces = {};
var meetingrooms = {};
var meetingroomCount = 0;
var usageMeetingroom = 0;
var selMeetingroom = null;

$(document).ready(function(e) {
	 $(".select1").uedSelect({
			width : 345			  
	});
	$(".select2").uedSelect({
		width : 167  
	});
	$(".select3").uedSelect({
		width : 100
	});
	
	
	$("div[name='noSpace']").show();
	$("div[name='noMeetingroom']").hide();
	$("div[name='something']").hide();
	
	
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#btnDelete").click(deleteData);
	$(".deleteMeetingRoom").click(deleteMeetingRoom);
	$("#add").click(add);
	
	
	initialPlaces();

	$("SELECT[name='placeProvinceSelect']").change(provinceChange);	
	$("SELECT[name='placeCitySelect']").change(initialSpace);
	$("SELECT[name='spaceSelect']").change(spaceChange);
	$("input[type='file'][name='file']").change(uploadSpaceImage);
	

});

function getRequestJson(requestJson){	
	if(requestJson == null){
		requestJson = {};
	}
	var addmeetingroomStatus = $("#addmeetingroomStatus").val();
	if(addmeetingroomStatus == '-1'){
		alert("请选择会议室状态");
		return false;
	}
	$("[formParameter]").each(function(index,element){
		try{
			var required = $(element).prop("required");
			var val = $(element).val();
			var name = $(element).attr("name");
			if(required == '1' && $.trim(val) == ''){
				var message = $(element).attr("message");
				alert(message);
				requestJson = false;
				return false;
			}
			requestJson[name] = $(element).val();
		}catch(e){
			//alert(e.message);
		}
	});
	if(requestJson != false){	
		var mSpace = spaces[$("#searchSpace").val()];		
		requestJson["space"] = mSpace;
		try{
			requestJson["province"] = mSpace.province;
			requestJson["city"] = mSpace.city;
		}catch(e){
			console.log(e.message);
		}		
//		requestJson["province"] = provinces[$("#searchProvince").val()];		
//		requestJson["city"] = cities[$("#searchCity").val()];		
//		requestJson["space"] = spaces[$("#searchSpace").val()];
	}
	return requestJson;
}



function save(){
	
	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/meetingroom/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='dataList']").show();
        	$("DIV[name='dataAdd']").hide();
        	search(1);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function update(data){
	if(data == null){
		return false;
	}
	data = getRequestJson(data);
	if(data == false){
		return false;
	}
	
	
	$.ajax({
        url: '/euc/meetingroom/update',
        data:JSON.stringify(data),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	//alert(result);
        	$("DIV[name='dataList']").show();
        	$("DIV[name='dataAdd']").hide();
        	search(1);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataAdd']").hide();
}

function clearForm(){
	$("[formParameter]").each(function(index,element){		
		try{			
			var tagName = $(element).prop("tagName");
			if(tagName == 'SELECT'){
				var firstValue = $(element).find('option').eq(0).val();
				$(element).val(firstValue).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			//alert(e.message);
		}
		$("#meetingroomImage").prop("src",'');
		$("input[name='displayPicture']").val('');
		$("input[type='file'][name='file']").val('');
		
	});
	if($("#searchSpace").val() == '0'){
		alert("请选择空间");
		return false;
	}else{
		$("#formSpaceName").html(spaces[$("#searchSpace").val()].spaceName);
	}
	return true;
}

function setForm(data){
	$("[formParameter]").each(function(index,element){
		try{
			var tagName = $(element).prop("tagName");
			if(tagName == 'SELECT'){				
				$(element).val(data[$(element).attr("name")]).trigger('change');
			}else{
				$(element).val(data[$(element).attr("name")]);
			} 
		}catch(e){
			//alert(e.message);
		}
	});
	$("#meetingroomImage").prop("src",data.displayPicture);
	$("input[name='displayPicture']").val(data.displayPicture);
}

function add(){
	if(clearForm() == false){
		return false;
	}
	$("#operator").html("添加");	
	$("#btnDelete").hide();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataAdd']").show();
    $("#addmeetingroomStatus").val("-1").trigger("change");
}


function detail(){
	//alert($(this).attr('id'));
	var meetingRoomId = $(this).attr('id');
	var meetingroom = meetingrooms[meetingRoomId];
	if(meetingroom != null){
		selMeetingroom = meetingroom;
		$("#btnDelete").show();
		clearForm();
		setForm(meetingroom);
		$("#btnDelete").show();
		$("#operator").html("编辑");
		$("DIV[name='dataList']").hide();
		$("DIV[name='dataAdd']").show();	
		//popupModalDialog();
		$("#btnSave").unbind();
		$("#btnSave").click(function(){
			update(meetingrooms[meetingRoomId]);
		});
	}	
}

function deleteMeetingRoom(){
    var meetingRoomId = $(this).attr('id');
    var meetingroom = meetingrooms[meetingRoomId];
    if(meetingroom != null){
        selMeetingroom = meetingroom;
        clearForm();
        setForm(meetingroom);
        deleteData();
        clearForm();
	}
}

function deleteData(){
	if(selMeetingroom != null){
		if(confirm("确定删除该会议室?")){
			selMeetingroom["enable"] = false;
			update(selMeetingroom);
		}
	}	 
}

function search(currentPage){	
	var parameter = $("INPUT[name='parameter']").val();
	var provinceId = $("#searchProvince").val();
	// if(provinceId == '0'){
	// 	alert("请选择省");
	// 	return;
	// }
	// var cityId = $("#searchCity").val();
	// if(cityId == '0'){
	// 	alert("请选择市");
	// 	return;
	// }
	var spaceId = $("#searchSpace").val();
	if(spaceId == '0'){
		alert("请选空间");
		return;
	}
	meetingroomCount = 0;
	usageMeetingroom = 0;
	// var requestJson = {currentPage:currentPage,data:{like:{meetingroomName:parameter},equals:{'province.provinceId':provinceId,'city.cityId':cityId,'space.id':spaceId}}};
	var requestJson = {currentPage:currentPage,data:{like:{meetingroomName:parameter},equals:{'space.id':spaceId}}};
	$.ajax({
        url: '/euc/meetingroom/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#meetingroomList").empty();
        	$.each(result.data.list,function(i,data){
        		var meetingroomStatus = 'meetingroomBlockStop';
        		if(data.meetingroomStatus == '启用'){
	        		usageMeetingroom = usageMeetingroom + 1;
	        		meetingroomStatus = 'meetingroomBlock';
	        	}
				var html = '<li>';				
				html += '<div class="'+ meetingroomStatus +'">';
				html += '<p>'+data.meetingroomName+'</p>';
				html += '<ul class="meetingCon" >';
				html += '<li><span>容纳人数&nbsp;&nbsp;：</span><span>'+ data.seatCount +'</span></li>';
				html += '<li><span>当前预约会议&nbsp;&nbsp;：</span><span>0</span></li>';       
				html += '<li><span>可预订时间&nbsp;&nbsp;：</span><span>'+ data.bookStartTime +'--'+ data.bookEndTime +'</span></li>';
				html += '<li><span>租赁单价&nbsp;&nbsp;：</span><span>'+ data.meetingroomPrice  +'元/30分钟</span></li>'; 
				html += '</ul>';
				html += '<div class="meetingroomInf">';
				html += '<ul>';				
				html += '<li class="appointment" onclick="orderlist(\''+data.meetingroomName+'\')" id="'+data.id+'">查看预约</li>';
				html += '<li class="meetingroomInfEditor" id="'+data.id+'">编辑</li>	';				
				html += '<li class="deleteMeetingRoom" id="'+data.id+'">删除</li>	';
				html += '</ul>';
				html += '</div>';
				html += '</div>';
				html += '</li>';
	        	$("#meetingroomList").append(html);
	        	dataList[data.id] = data;
	        	meetingrooms[data.id] = data;
	        	meetingroomCount = i + 1;
			});
        	
        	if(result.data.list.length > 0){
        		$("div[name='noSpace']").hide();
            	$("div[name='noMeetingroom']").hide();
            	$("div[name='something']").show();
        	}else{
        		$("div[name='noSpace']").hide();
            	$("div[name='noMeetingroom']").show();
            	$("div[name='something']").hide();
        	}
        	$("#usage").html(usageMeetingroom);
        	$("#meetingroomCount").html(meetingroomCount);        	
        	$('li .meetingroomInfEditor').click(detail);
			$('li .deleteMeetingRoom').click(deleteMeetingRoom);
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function orderlist(name){
	window.location.href="meetingRoomOrderList.html?name="+encodeURI(name);
}
function initialPlaces(){
	$.ajax({
        url: '/euc/space/province',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async:true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var provinceSelect = $("SELECT[name='placeProvinceSelect']");        	
        	$.each(result,function(index,data){	
           		$('<option value="'+ data.provinceId +'">'+ data.provinceName +'</option>').appendTo($(provinceSelect));
           		provinces[data.provinceId] = data;
           		var citiesSelect = $("SELECT[name='placeCitySelect']");           		
           		$.each(data.cities,function(index,city){	
    	       		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
    	       		cities[city.cityId] = city;	
    			});
   			});	    	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
	

    var spaceSelect = $("SELECT[name='spaceSelect']");
    //获取全部空间列表
    $.ajax({
        url: '/euc/space/list',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
            $.each(result,function(index,data){
                if(index == 0){
                    firstOptionValue = data.id;
                }
                $('<option value="'+ data.id +'">'+ data.spaceName +'</option>').appendTo($(spaceSelect));
                spaces[data.id] = data;
            });
        },
        error: function () {
			/*alert("error");*/
        }
    });
    
}

function provinceChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var citiesSelect = $("SELECT[name='placeCitySelect']");
	$(citiesSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(citiesSelect));
	if(provinceIdSelected != '0'){
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(citiesSelect));
		});
	}
	$(citiesSelect).val(0).trigger('change');
}

function initialSpace(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceSelect));	
	if(cityIdSelected == '0'){
		$(spaceSelect).val(0).trigger('change');
		return;		
	}
	var spacesList = citySpace[cityIdSelected];
	if(spacesList == null){
		var requestJson = {data:{like:{spaceName:''},equals:{'city.cityId':cityIdSelected}}};
		$.ajax({
	        url: '/euc/space/find',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: false,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	//alert(JSON.stringify(result));
	        	citySpace[cityIdSelected] = result;
	        	spacesList = result;
	        },
	        error: function () {
	        	/*alert("error");*/
	        }  
	    });
	} 	
	$.each(spacesList,function(index,data){	
   		$('<option value="'+ data.id +'">'+ data.spaceName +'</option>').appendTo($(spaceSelect));
   		spaces[data.id] = data;
	});
	$(spaceSelect).val(0).trigger('change');
}

function spaceChange(){
	return;
	var spaceId=$(this).children('option:selected').val();
	if(spaceId != '0'){
		$("div[name='noSpace']").show();
		$("div[name='noMeetingroom']").hide();
		$("div[name='something']").hide();
	}else{
		$("div[name='noSpace']").show();
		$("div[name='noMeetingroom']").hide();
		$("div[name='something']").hide();
	}
}

function uploadSpaceImage(){
	
	 var fileName = $("#uploadFile").val();
		
	 var dom = document.getElementById("uploadFile");
	 var fileSize = dom.files[0].size;
	 if (fileSize > 10000000) {
		 alert("上传文件过大,请上传小于10M的图片");
		 $("#uploadFile").val("");
		 return false;
	}
	var fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLocaleLowerCase();
	if (fileType != 'jpg' && fileType != 'bmp' && fileType != 'png' && fileType != 'gif' && fileType != "jpeg") {
		alert("图片只能上传JPG,JPEG,BMP,PNG,GIF格式的图片！");
		$("#uploadFile").val("");
		return false;
	}
	
	var accessToken = localStorage.getItem('accessToken');
	$('#meetingroomForm').ajaxSubmit({
		dataType : "json",
		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
		beforeSubmit : function(request) { 
			//alert("正在上传"); 
		}, 
		success : function(result, textStatus, response) { 
			//alert(JSON.stringify(result));
			$("#meetingroomImage").prop("src",result.fileUrl);
			$("input[name='displayPicture']").val(result.fileUrl);
			//alert('成功上传！'); 
		 
		},
		error : function(result) {
			//alert('上传失败！'); 
		} 
	});
}